package hu.monitor.server.agent;

import hu.monitor.server.AgentMaintenance;
import hu.monitor.server.AgentNotFoundException;
import hu.monitor.server.db.Agent;

import java.net.InetSocketAddress;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Stateless
public class AgentMaintenanceBean implements AgentMaintenance {
	private static Logger log = LoggerFactory.getLogger(AgentMaintenanceBean.class);

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public Integer registerEndpoint(final Integer agentId, final String agentName, final InetSocketAddress endpoint) throws AgentNotFoundException {
		log.info("registering agent, agentId: {}, agentName: {}, endpoint: {}", agentId, agentName, endpoint);
		final Agent agent;
		boolean newAgent;
		if (agentId != null) {
			newAgent = false;
			agent = this.entityManager.find(Agent.class, agentId);
			if (agent == null) {
				throw new AgentNotFoundException("Agent not found with id "+agentId);
			}
		} else {
			newAgent = true;
			agent = new Agent();
		}
		agent.setName(agentName);
		final String host = endpoint.getHostString();
		final int port = endpoint.getPort();
		agent.setEndpointAddress("socket://"+host+":"+port);
		if (newAgent) {
			this.entityManager.persist(agent);
		}
		return agent.getId();
	}

}
